package com.xiaoyu.client.ui.activity.forum;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.forum.ForumReplyOneRecyAdapter;
import com.xiaoyu.client.model.forum.ForumDetailBean;
import com.xiaoyu.client.model.forum.ForumDetailBean.DataBean.ForumReplayBean;
import com.xiaoyu.client.model.forum.ForumParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.PhotoViewActivity;
import com.xiaoyu.client.ui.activity.help.UserSeekInfoActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.MediaUtils;
import com.xiaoyu.commonlib.utils.StatusBarUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCUtils;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

/**
 * 论坛详情
 */
public class ForumDetailActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String USER_ID = "forum_detail_user_id";
    private ImageView backBtn;//返回
    private ImageView shareBtn;//分享
    private TextView attentedBtn;//关注
    private LinearLayout userLayout;//用户信息容器
    private CCircleImageView photoImg;//发帖人的头像
    private TextView nameTxt;//发帖人的昵称
    private TextView timeTxt;//帖子的发布时间
    private TextView contentTxt;//帖子文字内容
    private TextView adressTxt;//帖子发布地址
    private TextView replyNumTxt;//帖子回复量
    private RelativeLayout videoImgLayout;//视频、图片内容区域
    private LinearLayout smallLayout;//小图区域
    private ImageView bigImg;//大图
    private JCVideoPlayerStandard videoPlayer;//视频
    private EditText inputEdit;//评论编辑框
    private LinearLayout likeBtn;//点赞按钮
    private LinearLayout collectBtn;//收藏按钮
    private TextView likeTxt;//点赞文字
    private ImageView likeImg;//点赞图标
    private ImageView collectImg;//收藏图标
    private RecyclerView mReplyLayout;//回帖列表容器
    private SmartRefreshLayout mRefreshLayout;//刷新控件
    private TextView mIssueTxt;//发布
    private ForumReplyOneRecyAdapter mAdapter;
    private int page = 1;//页数
    private int totalPage;//总页数
    private String forumId;//帖子id
    private String userId;//发帖人用户id
    private List<ForumReplayBean> mReplyList = new ArrayList<>();//帖子回复数据

    private boolean isAttention;//是否关注
    private boolean isLike;//是否点赞
    private boolean isCollect;//是否收藏

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_detail);

        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        StatusBarUtil.StatusBarLightMode(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorWhite));
        }

        parseIntent();
        initView();
    }

    //接收其他页面传过来的值
    private void parseIntent() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            forumId = bundle.getString(ClientConstants.FORUM_ID);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        mReplyList.clear();
        getForumInfo();
    }

    //初始化控件
    private void initView() {
        backBtn = findViewById(R.id.activity_forum_detail_title_back_btn);
        shareBtn = findViewById(R.id.activity_forum_detail_title_share_btn);
        attentedBtn = findViewById(R.id.activity_forum_detail_problem_attention_btn);
        userLayout = findViewById(R.id.activity_forum_detail_problem_user_info_layout);
        photoImg = findViewById(R.id.activity_forum_detail_problem_portrait);
        nameTxt = findViewById(R.id.activity_forum_detail_problem_name_txt);
        timeTxt = findViewById(R.id.activity_forum_detail_problem_publish_time_txt);
        contentTxt = findViewById(R.id.activity_forum_detail_problem_content_txt);
        videoImgLayout = findViewById(R.id.activity_forum_detail_video_img_layout);
        videoPlayer = findViewById(R.id.activity_forum_detail_video_player);
        smallLayout = findViewById(R.id.activity_forum_detail_small_picture);
        bigImg = findViewById(R.id.activity_forum_detail_big_picture);
        adressTxt = findViewById(R.id.activity_forum_detail_problem_locate_txt);
        replyNumTxt = findViewById(R.id.activity_forum_detail_problem_reply_num_txt);
        inputEdit = findViewById(R.id.activity_forum_detail_reply_edit_box);
        likeBtn = findViewById(R.id.activity_forum_detail_like_layout);
        collectBtn = findViewById(R.id.activity_forum_detail_collect_layout);
        likeTxt = findViewById(R.id.activity_forum_detail_like_txt);
        likeImg = findViewById(R.id.activity_forum_detail_like_img);
        collectImg = findViewById(R.id.activity_forum_detail_collect_img);
        mReplyLayout = findViewById(R.id.activity_forum_detail_reply_list_container);
        mRefreshLayout = findViewById(R.id.activity_forum_detail_reply_refresh_layout);
        mIssueTxt = findViewById(R.id.activity_forum_detail_issue_txt);
        mIssueTxt.setOnClickListener(this);

        initRecy();

        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setNoMoreData(false);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);

        inputEdit.setSingleLine(true);
        inputEdit.setImeOptions(EditorInfo.IME_ACTION_DONE);
        inputEdit.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        inputEdit.setOnEditorActionListener(onEditorActionListener);
        inputEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (inputEdit.getText().length() > 0) {
                    collectBtn.setVisibility(View.GONE);
                    mIssueTxt.setVisibility(View.VISIBLE);
                }
            }
        });

        backBtn.setOnClickListener(this);
        shareBtn.setOnClickListener(this);
        userLayout.setOnClickListener(this);
        attentedBtn.setOnClickListener(this);
        likeBtn.setOnClickListener(this);
        collectBtn.setOnClickListener(this);

    }

    private void initRecy() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mReplyLayout.setLayoutManager(manager);
        mAdapter = new ForumReplyOneRecyAdapter(this, mReplyList);
        mReplyLayout.setAdapter(mAdapter);
        mReplyLayout.setNestedScrollingEnabled(false);
    }

    @Override
    public void onClick(View v) {
        if (v == backBtn) {//返回
            onBackPressed();
        } else if (v == shareBtn) {//分享
            if (!UMShareAPI.get(this).isInstall(this, SHARE_MEDIA.WEIXIN)) {
                ToastUtil.showBelowToast(this, "您还未安装微信");
                return;
            }
            toShare();
        } else if (v == attentedBtn) {//关注
            toAttention();

        } else if (v == likeBtn) {//点赞
            if (!isLike) {//未点赞
                toLike();
            }
        } else if (v == collectBtn) {//收藏
            toCollect();
        } else if (v == userLayout) {//用户信息
            Intent intent = new Intent(this, UserSeekInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(ClientConstants.FROM, ClientConstants.FROM_FORUM_DETAIL);
            bundle.putString(USER_ID, userId);
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (v == mIssueTxt) {
            //先隐藏键盘
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getCurrentFocus()
                            .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            toReply();
        }
    }


    /**
     * 设置软键盘按钮监听
     */
    private TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_DONE) {
                String inputContent = inputEdit.getText().toString();
                if (TextUtils.isEmpty(inputContent)) {
                    ToastUtil.showToast(ForumDetailActivity.this, "请输入评论内容！");
                } else {
                    //先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    toReply();
                }
                return true;
            }
            return false;

        }
    };


    //加载更多
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getForumInfo();
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(false);
            } else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showBelowToast(ForumDetailActivity.this, "我是有底线的...");
            }
        }
    };

    /**
     * 获取论坛详情
     */
    private void getForumInfo() {
        NetworkManager.getForumDetail(page, forumId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                praseForumInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }

    private void praseForumInfoSuc(String result) {
        ToastUtil.logResult("论坛帖子详情", result);
        if (page == 1) {
            mReplyList.clear();
            mAdapter.notifyDataSetChanged();
        }
        ForumDetailBean bean = new Gson().fromJson(result, ForumDetailBean.class);

        if (bean.getData().getReplay().size() != 0) {
            mReplyList.addAll(bean.getData().getReplay());
            mAdapter.notifyDataSetChanged();
        }
        userId = bean.getData().getFourmcontent().getUserid();
        totalPage = bean.getData().getCount();
        replyNumTxt.setText(bean.getData().getFourmcontent().getFourmReplayNum().equals("") ? "回复0" : "回复 " + bean.getData().getFourmcontent().getFourmReplayNum());
        staffData(bean.getData().getFourmcontent());
    }

    //绑定帖子内容数据
    private void staffData(final ForumParam fourmcontent) {
        Glide.with(this).load(fourmcontent.getUserphoto()).into(photoImg);
        nameTxt.setText(fourmcontent.getNickname());
        isAttention = fourmcontent.isAttention();
        isCollect = fourmcontent.isCollect();
        isLike = fourmcontent.isLike();
        if (fourmcontent.isAttention()) {//已关注
            attentedBtn.setText("已关注");
        } else {
            attentedBtn.setText("关注");
        }
        if (fourmcontent.isCollect()) {//已收藏
            collectImg.setImageResource(R.drawable.icon_shoucang_pressed);
        } else {
            collectImg.setImageResource(R.drawable.icon_shoucang_normal);
        }
        if (fourmcontent.isLike()) {//已点赞
            likeBtn.setEnabled(false);
            likeTxt.setEnabled(false);
            likeImg.setImageResource(R.drawable.icon_dianzan_pressed);
            likeTxt.setText("已赞");
        } else {
            likeBtn.setEnabled(true);
            likeTxt.setEnabled(true);
            likeImg.setImageResource(R.drawable.icon_dianzan_normal);
            likeTxt.setText("点赞");
        }
        timeTxt.setText(fourmcontent.getFourmtime());
        contentTxt.setText(fourmcontent.getFourmtitle());
        if (fourmcontent.getBig() == 1) {//文字
            videoImgLayout.setVisibility(View.GONE);
        } else if (fourmcontent.getBig() == 2) {//大图
            videoImgLayout.setVisibility(View.VISIBLE);
            bigImg.setVisibility(View.VISIBLE);
            smallLayout.setVisibility(View.GONE);
            videoPlayer.setVisibility(View.GONE);
            Glide.with(this).load(fourmcontent.getFourmimg().get(0)).into(bigImg);
            bigImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ForumDetailActivity.this, PhotoViewActivity.class);
                    intent.putExtra(ClientConstants.IMAGER_LIST_URL, (Serializable) fourmcontent.getFourmimg());
                    intent.putExtra(ClientConstants.IMAGER_CLICK_POS, 0);
                    startActivity(intent);
                }
            });
        } else if (fourmcontent.getBig() == 3) {//小图
            videoImgLayout.setVisibility(View.VISIBLE);
            smallLayout.setVisibility(View.VISIBLE);
            bigImg.setVisibility(View.GONE);
            videoPlayer.setVisibility(View.GONE);
            for (int i = 0; i < fourmcontent.getFourmimg().size(); i++) {
                if (i < smallLayout.getChildCount()) {
                    Glide.with(this)
                            .load(fourmcontent.getFourmimg().get(i))
                            .into(((ImageView) smallLayout.getChildAt(i)));
                    final int finalI = i;
                    smallLayout.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(ForumDetailActivity.this, PhotoViewActivity.class);
                            intent.putExtra(ClientConstants.IMAGER_LIST_URL, (Serializable) fourmcontent.getFourmimg());
                            intent.putExtra(ClientConstants.IMAGER_CLICK_POS, finalI);
                            startActivity(intent);
                        }
                    });

                }
            }
        } else if (fourmcontent.getBig() == 4) {//视频
            videoImgLayout.setVisibility(View.VISIBLE);
            smallLayout.setVisibility(View.GONE);
            bigImg.setVisibility(View.GONE);
            videoPlayer.setVisibility(View.VISIBLE);
            String videoUrl = fourmcontent.getFourmvideo();

            videoPlayer.setUp(videoUrl,
                    JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "");
            MediaUtils.getImageForVideo(videoUrl, new MediaUtils.OnLoadVideoImageListener() {
                @Override
                public void onLoadImage(Bitmap bitmap) {
                    videoPlayer.thumbImageView.setImageBitmap(bitmap);
                }
            });
            videoPlayer.backButton.setVisibility(View.INVISIBLE);
            videoPlayer.tinyBackImageView.setVisibility(View.INVISIBLE);
        }
        adressTxt.setText(fourmcontent.getFourmress());
        replyNumTxt.setText("回复 " + fourmcontent.getFourmReplayNum());
    }


    /**
     * 帖子点赞
     */
    private void toLike() {
        NetworkManager.likeForum(forumId, true, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                Toast.makeText(ForumDetailActivity.this, "点赞click", Toast.LENGTH_SHORT).show();
                likeBtn.setEnabled(false);
                likeTxt.setEnabled(false);
                likeImg.setImageResource(R.drawable.icon_dianzan_pressed);
                likeTxt.setText("已赞");
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                if (errorCode.equals("y402")) {
                    Toast.makeText(ForumDetailActivity.this, "已点赞", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    /**
     * 帖子收藏
     */
    private void toCollect() {
        NetworkManager.collectOrCancleForum(forumId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                if (isCollect) {//已收藏
                    isCollect = false;
                    collectImg.setImageResource(R.drawable.icon_shoucang_normal);
                } else {
                    isCollect = true;
                    collectImg.setImageResource(R.drawable.icon_shoucang_pressed);
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {


            }
        });
    }

    /**
     * 帖子关注
     */
    private void toAttention() {
        NetworkManager.sendAttentionUser(userId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                if (isAttention) {
                    isAttention = false;
                    attentedBtn.setText("关注");
                } else {
                    isAttention = true;
                    attentedBtn.setText("已关注");
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }


    /**
     * 帖子回复
     */
    private void toReply() {
        NetworkManager.sendForumReply(forumId, inputEdit.getText().toString(), String.valueOf(0), new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                inputEdit.setText("");
                page = 1;
                mReplyList.clear();
                getForumInfo();

                collectBtn.setVisibility(View.VISIBLE);
                mIssueTxt.setVisibility(View.GONE);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }


    /**
     * 发送分享
     */
    private void toShare() {
        UMImage image = new UMImage(this, R.drawable.share_logo);//网络图片
        image.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩，默认为大小压缩，适合普通很大的图
        image.compressStyle = UMImage.CompressStyle.QUALITY;//质量压缩，适合长图的分享
        //压缩格式设置
        image.compressFormat = Bitmap.CompressFormat.PNG;//用户分享透明背景的图片可以设置这种方式，但是qq好友，微信朋友圈，不支持透明背景图片，会变成黑色

        UMWeb web = new UMWeb(ClientConstants.Share_Forum_Url + forumId);
        web.setTitle("你身边的卡车之家");//标题
        web.setThumb(image);  //缩略图
        web.setDescription("汽车、汽车配件、汽车用品的销售及网上销售，汽车配件的修理服务，车辆信息咨询服务，商务信息咨询服务，广告设计、制作、代理、发布。（依法须经批准的项目，经相关部门批");//描述

        new ShareAction(this).withMedia(web).
                setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA)
                .setCallback(shareListener).open();
    }

    /**
     * 友盟分享回调
     */
    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtil.showBelowToast(ForumDetailActivity.this, "分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Log.i("xiaoyuu", "分享失败  原因：" + t.toString());
            ToastUtil.showBelowToast(ForumDetailActivity.this, "分享失败");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.showBelowToast(ForumDetailActivity.this, "取消了分享");
        }
    };


    @Override
    public void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
        JCUtils.getAppCompActivity(this).getSupportActionBar().hide();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
